package com.projectx.action.talk;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.text.TextPaint;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ActionMenuView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.menu.MenuBuilder;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.bumptech.glide.Glide;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.bottomnavigation.BottomNavigationView.OnNavigationItemSelectedListener;
import com.google.gson.Gson;
import com.projectx.R;
import com.projectx.action.contact.ContactListFragment;
import com.projectx.action.contact.CreateGroupActivity;
import com.projectx.action.contact.DeleteContact;
import com.projectx.action.contact.Findfriend;
import com.projectx.action.contact.TabFragment;
import com.projectx.action.contact.ContactListFragment;
import com.projectx.action.contact.CreateGroupActivity;
import com.projectx.action.contact.DeleteContact;
import com.projectx.action.contact.FindFriend;
import com.projectx.action.MainActivity;
import com.projectx.action.SettingActivity;
import com.projectx.dao.UserDataDao;
import com.projectx.entity.User;
import com.projectx.util.ActivityManage;
import com.projectx.util.PermissionUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 这个是底部bottomNavigation的各个界面的容器界面
 */
public class TalkListActivity extends AppCompatActivity{
    private User userData;
    public static String username;
    public static String password;
    private ImageButton headImage;
    private static boolean mBackKeyPressed = false;
    private Fragment[] fragments;
    private int lastFragmentIndex;
    private OnNavigationItemSelectedListener onNavigationItemSelectedListener= new OnNavigationItemSelectedListener(){

        /**
         * 这里是选中某个界面执行的操作
         * @param item 当前选中的菜单
         * @return 是否成功选中
         */
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            MaterialToolbar materialToolbar = findViewById(R.id.TalkListBar);
            switch (item.getItemId()){
                case R.id.navigation_current_talk:
                    enterCurrentTalkList(materialToolbar);
                    setFragment(0);
                    return true;
                case R.id.navigation_contacts:
                    enterContacts(materialToolbar);
                    setFragment(1);
                    return true;
                case R.id.navigation_identify:
                    enterIdentity(materialToolbar);
                    setFragment(2);
                    return true;
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        PermissionUtil.verifyStoragePermissions(this);
        super.onCreate(savedInstanceState);
        ActivityManage.addActivity("TalkListActivity",this);
        setContentView(R.layout.activity_talklist);
        final Intent accountIntent = getIntent();
        username = accountIntent.getStringExtra("accountName");
        password = accountIntent.getStringExtra("password");
        try {
            getSupportActionBar().hide(); //去除标题栏
        } catch (NullPointerException e){
            Log.d("KMH","没有状态栏标题");
        }

        final BottomNavigationView bottomNavigationView = findViewById(R.id.Navigation);
        bottomNavigationView.setSelectedItemId(R.id.navigation_current_talk);
        final MaterialToolbar toolbar = findViewById(R.id.TalkListBar);
        initFragment();//初始化Fragment
        enterCurrentTalkList(toolbar);//初始化分页，默认进入聊天记录
        bottomNavigationView.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener);
        headImage = findViewById(R.id.BarImage);//头像
        new Thread(userInfo).start();//加载图像
        headImage.setOnClickListener(new View.OnClickListener() { //为头像设置监听事件，跳转到身份
            @Override
            public void onClick(View v) {
                if (bottomNavigationView.getSelectedItemId() != R.id.navigation_identify){
                    bottomNavigationView.setSelectedItemId(R.id.navigation_identify);//跳转到身份页
                    enterIdentity(toolbar);
                }
            }
        });


        TextView barAccountText = findViewById(R.id.BarAccount);
        barAccountText.setText(username);
        TextPaint textPaint = barAccountText.getPaint();
        textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        textPaint.setStrokeWidth(2);
    }

    /**
     * 进入聊天记录界面，为顶部按钮设置监听
     * @param materialToolbar 底部栏引用
     */
    private void enterCurrentTalkList(MaterialToolbar materialToolbar){
        materialToolbar.getMenu().clear();
        getMenuInflater().inflate(R.menu.current_talk_bar_menu,materialToolbar.getMenu());
        materialToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()){
                    case R.id.delete:
                        AlertDialog.Builder alert = new AlertDialog.Builder(TalkListActivity.this);
                        alert.setMessage("确认删除所有聊天记录");
                        alert.setTitle("警告");
                        alert.setNegativeButton("取消",null);
                        alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                UpdateCurrentTalk updateCurrentTalk = (CurrentTalkFragment)fragments[0];
                                updateCurrentTalk.deleteAll();
                                //删除聊天数据库
                            }
                        });
                        alert.show();
                        return true;
                    case R.id.search_talk_list:
                        Toast.makeText(TalkListActivity.this,"暂不支持",Toast.LENGTH_SHORT).show();
                        return true;
                }
                return false;
            }
        });
    }

    /**
     *进入联系人界面，为顶部按钮设置监听
     * @param materialToolbar 底部状态栏引用
     */
    private void enterContacts(MaterialToolbar materialToolbar){
        materialToolbar.getMenu().clear();
        getMenuInflater().inflate(R.menu.contact_bar_menu,materialToolbar.getMenu());
        materialToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()){
                    case R.id.add_contact:
                        Intent intent=new Intent(TalkListActivity.this, FindFriend.class);
                        startActivity(intent);
                        //启动添加联系人界面
                        return true;
                    case R.id.search_contact:
                        //启动搜索界面
                        Intent intent2=new Intent(TalkListActivity.this, CreateGroupActivity.class);
                        startActivity(intent2);
                        //Toast.makeText(TalkListActivity.this,"暂不支持",Toast.LENGTH_SHORT).show();
                        return true;
                    case R.id.delete:
                        Intent intent1=new Intent(TalkListActivity.this, DeleteContact.class);
                        startActivity(intent1);
                }
                return false;
            }
        });
    }

    /**
     * 进入个人中心界面，为顶部按钮设置监听
     * @param materialToolbar 底部引用
     */
    private void enterIdentity(MaterialToolbar materialToolbar) {
        materialToolbar.getMenu().clear();
        getMenuInflater().inflate(R.menu.identity_bar_menu,materialToolbar.getMenu());
        materialToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.logout){
                    AlertDialog.Builder alert = new AlertDialog.Builder(TalkListActivity.this);
                    alert.setTitle("注销登录");
                    alert.setMessage("是否注销登录");
                    alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(TalkListActivity.this,MainActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                            startActivity(intent);
                            UserDataDao userDataDao = new UserDataDao();
                            userDataDao.logoutUser(username);
                            ActivityManage.removeAllActivityExcept("MainActivity");
                        }
                    });
                    alert.setNegativeButton("取消",null);
                    alert.show();
                    return true;
                } else if(item.getItemId() == R.id.setting){
                    Intent intent = new Intent(TalkListActivity.this, SettingActivity.class);
                    intent.putExtra("accountName",getIntent().getStringExtra("accountName"));
                    startActivity(intent);
                }
                return false;
            }
        });
    }

    /**
     * 初始化Fragment
     */
    private void initFragment(){
        fragments = new Fragment[]{new CurrentTalkFragment(),new ContactListFragment(),new IdentityFragment()};
        getSupportFragmentManager().beginTransaction().add(R.id.FriendListFragment,fragments[0]).show(fragments[0]).commit();
        lastFragmentIndex = 0;
    }

    /**
     * 切换Fragment
     * @param index 主页索引，0是CurrentTalk，1是ContactsFragment，2是IdentityFragment
     */
    private void setFragment(int index){
        if (lastFragmentIndex == index){
            return;
        }
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!fragments[index].isAdded()){
            transaction.add(R.id.FriendListFragment,fragments[index]);
        }
        transaction.hide(fragments[lastFragmentIndex]);
        transaction.show(fragments[index]);
        transaction.commit();
        lastFragmentIndex = index;
    }

    /**
     * 双击返回键退出
     */
    @Override
    public void onBackPressed() {
        if(!mBackKeyPressed){
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mBackKeyPressed = true;
            new Timer().schedule(new TimerTask() {//延时两秒，如果超出则擦错第一次按键记录
                 @Override
                 public void run() {
                     mBackKeyPressed = false;
                 }
                 }, 2000);
        } else {//退出程序
            ActivityManage.removeAllActivity();
            this.finish();
            System.exit(0);
        }
    }

    /**
     * 加载网络头像任务
     */
    private FutureTask<User> userInfo = new FutureTask<>(new Callable<User>() {
        @Override
        public User call() {
            try {
                Socket socket = new Socket("106.15.192.117", 2333);
                Gson gson = new Gson();
                User user = new User();
                user.setFlag(4);
                user.setUserName(username);
                user.setPassword(password);
                String message = gson.toJson(user);
                DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                dataOutputStream.writeUTF(message);
                dataOutputStream.flush();
                DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                String netStr = dataInputStream.readUTF();
                try {
                    JSONObject getMessage = new JSONObject(netStr);
//                    Log.d("kmh", "Talk list call: " + getMessage.toString());
                    if (getMessage.getInt("code") == -1){
                        throw new Exception("服务器错误");
                    } else if (getMessage.getInt("code") == 0){
                        userData = gson.fromJson(getMessage.getString("data"),User.class);
                        if (userData != null){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Log.d("kmh", "TalkList run: " + userData.getPic());
                                    Glide.with(TalkListActivity.this)
                                            .load(userData.getPic())
                                            .into(headImage);
                                }
                            });

                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.d("kmh", "Talk List doInBackground: 后端JSON字符串有问题祭天吧");
                } catch (Exception e){
                    e.printStackTrace();
                    Log.d("kmh", "Talk List call: 后端服务器错误");
                } finally {
                    dataInputStream.close();
                    dataOutputStream.close();
                    socket.close();
                }

            } catch (Exception ioe) {
                ioe.printStackTrace();
            }
            return null;
        }
    });

}

